package br.com.engine.componentes;

import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;

import br.com.engine.controle.ControleBase;
import br.com.engine.menu.Menu;

public abstract class Scene
{
	private List<GameObject> lGameObjects = new ArrayList<GameObject>( );
	
	public Scene( )
	{
	    
	}

	public void setup( )
	{
	    
	}
	
	public void draw( Graphics2D g2 ) 
	{
		lGameObjects.forEach( item -> 
		{
			item.getComponentes( );
			
			Sprite      sprite = item.getComponent( Sprite.class      );
			SpriteDebug debug  = item.getComponent( SpriteDebug.class );
			SpriteFont  font   = item.getComponent( SpriteFont.class  );
			Menu        menu   = item.getComponent( Menu.class        );
			
			drawSprite( g2,    item,   sprite );
			drawDebug ( debug, sprite, item   );
			drawFont  ( font,  g2             );
			drawMenu  ( menu                  );
		} );
	}

	private void drawMenu( Menu menu )
    {
	    if( menu != null )
	    {
	        menu.draw( );
	    }
    }

    private void drawFont( SpriteFont font, Graphics2D g )
	{
		if( font != null )
		{
		    font.createGraphics(g);
			font.draw( );
		}
	}

	private void drawDebug( SpriteDebug debug, Sprite sprite, GameObject item )
	{
		if( debug != null )
		{
			debug.height   = sprite.getImage( ).getHeight( );
			debug.width    = sprite.getImage( ).getWidth( );
			debug.position = item.getPosition( );	
			debug.draw( );
		}
	}

	private void drawSprite( Graphics2D g2d, GameObject obj, Sprite sp )
	{
		if( sp != null )
		{
			Graphics2D g = (Graphics2D)g2d.create( );	
			
			g.drawImage( sp.getImage( ), obj.getPosition( ).xp, obj.getPosition( ).yp, null );
			
			g.dispose( );
		}
	}
	
	public void update( long time ) 
	{		
		lGameObjects.forEach( item -> item.update( time ) );
	}
	
	public void add( GameObject obj )
	{
		if( ControleBase.isDebugMode( ) )
		{
			SpriteDebug sd = new SpriteDebug( );
			obj.addComponente( sd );
		}
		
		this.lGameObjects.add( obj );
	}
	
	public void remove( GameObject obj )
	{
		this.lGameObjects.remove( obj );
	}
	
	public void removeAll( List<GameObject> lObj )
	{
		this.lGameObjects.removeAll( lObj );
	}

    public void clearScene( )
    {
        removeAll( this.lGameObjects );
    }
}